﻿function cusGrid() {
    var pobj = {
        data: {},
        detailLink: [],
        rowbtns: [],
        toolbtns: [],
        cols: [],
        isSelect: true,
        tableName: '',
        isMultiple: false,
        pagination: true,
        showColumns: true,
        showToggle: true,
        cardView: false,
        pageSize: 10
    };

    var cur_detail_rid = -1;

    var rand = parseInt(Math.random() * 1000).toString();

    var getbtns = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
    }

    function init(obj) {
        for (var p in obj) {
            pobj[p] = obj[p];
        }
        pobj['data' + rand] = [];
        for (var i = 0; i < pobj.data.data.length; i++) {
            var p = $.extend(false, {}, pobj.data.data[i]);
            pobj['data' + rand].push(p);
        }
        //console.log(pobj);
        //initTable();
    }

    function initCard_mobile() {
        if (pobj.tableName == '') {
            return;
        }

        var rolebtns = getbtns('btns');
        rolebtns =  ',' + rolebtns + ','

        //init        
        for (var i = 0; i < pobj.cols.length; i++) {
            pobj.cols[i]['sortable'] = true;
        }
        if (pobj.isSelect) {
            pobj.cols.splice(0, 0, {
                checkbox: true
            });
        }
        if (pobj.rowbtns.length > 0) {
            pobj.cols.push({
                field: 'order',
                title: '操作'
            });
        }

        if (pobj.detailLink.length > 0) {
            pobj.cols.push({
                field: 'detail',
                title: '明细表'
            });
        }

        for (var i = 0; i < pobj.data.data.length; i++) {
            var p = pobj.data.data[i];
            var btnstr = '';
            for (var k = 0; k < pobj.rowbtns.length; k++) {
                var q = pobj.rowbtns[k];
                if (rolebtns == ',0,' || rolebtns.indexOf(',' + (k + pobj.toolbtns.length + 1) + ',') >= 0) {
                    if (q.jstr == undefined) {
                        btnstr = btnstr + '<button class="btn btn-default" onclick="' + pobj.tableName + '_init.edit(\'' + p.id + '\',\'' + rand + '\');' + q['fn'] + '();">' + q['text'] + '</button>';
                    } else {
                        btnstr = btnstr + q.jstr;
                    }
                }
            }
            if (btnstr != '') {
                pobj.data.data[i]['order'] = btnstr;
            }

            btnstr = '';
            for (var k = 0; k < pobj.detailLink.length; k++) {
                var q = pobj.detailLink[k];
                btnstr = btnstr + '<a class="btn btn-default" href="../' + q.tablename + '/index.html?parentid=' + p.id + '&btns=0">' + q.caption + '</a>';
            }
            if (btnstr != '') {
                pobj.data.data[i]['detail'] = '<br/>' + btnstr;
            }
        }

        var tbtnstr = '';
        for (var i = 0; i < pobj.toolbtns.length; i++) {
            var p = pobj.toolbtns[i];
            if (rolebtns == ',0,' || rolebtns.indexOf(',' + (i + 1) + ',') >= 0) {
                if (p.jstr == undefined) {
                    tbtnstr = tbtnstr + '<button class="btn btn-default" onclick="' + pobj.tableName + '_init.showalert(this);' + p['fn'] + '();">' + p['text'] + '</button>';
                } else {
                    tbtnstr = tbtnstr + p.jstr;
                }
            }
        }

        $('table[name="' + pobj.tableName + '"]:not(.table)').attr('data-unique', rand);
        $('table[name="' + pobj.tableName + '"]:not(.table)').bootstrapTable({
            columns: pobj.cols,
            data: pobj.data.data,
            toolbar: tbtnstr,
            pagination: true,
            search: true,
            searchOnEnterKey: true,
            singleSelect: pobj.isMultiple,
            locale: 'zh-CN',
            showColumns: pobj.showColumns,
            showToggle: false,
            cardView: true,
            detailView: false,
            pagination: true,
            pageSize: 5,
            rowAttributes: function (row, index) {
                return {
                    'data-idx': row.id
                };
            }
        });
        $('div.pull-right.search').removeClass('pull-right').addClass('pull-left');
    }

    function initTable() {
        if (pobj.tableName == '') {
            return;
        }

        var rolebtns = getbtns('btns');
        rolebtns =  ',' + rolebtns + ','

        //init        
        for (var i = 0; i < pobj.cols.length; i++) {
            pobj.cols[i]['sortable'] = true;
        }
        if (pobj.isSelect) {
            pobj.cols.splice(0, 0, {
                checkbox: true
            });
        }
        if (pobj.rowbtns.length > 0) {
            pobj.cols.push({
                field: 'order',
                title: '操作'
            });
        }

        for (var i = 0; i < pobj.data.data.length; i++) {
            var p = pobj.data.data[i];
            var btnstr = '';
            for (var k = 0; k < pobj.rowbtns.length; k++) {
                var q = pobj.rowbtns[k];
                if (rolebtns == ',0,' || rolebtns.indexOf(',' + (k + pobj.toolbtns.length + 1) + ',') >= 0) {
                    if (q.jstr == undefined) {
                        btnstr = btnstr + '<button class="btn btn-default" onclick="' + pobj.tableName + '_init.edit(\'' + p.id + '\',\'' + rand + '\');' + q['fn'] + '();">' + q['text'] + '</button>';
                    } else {
                        btnstr = btnstr + q.jstr;
                    }
                }
            }
            if (btnstr != '') {
                pobj.data.data[i]['order'] = btnstr;
            }
        }

        var tbtnstr = '';
        for (var i = 0; i < pobj.toolbtns.length; i++) {
            var p = pobj.toolbtns[i];
            if (rolebtns == ',0,' || rolebtns.indexOf(',' + (i + 1) + ',') >= 0) {
                if (p.jstr == undefined) {
                    tbtnstr = tbtnstr + '<button class="btn btn-default" onclick="' + pobj.tableName + '_init.showalert(this);' + p['fn'] + '();">' + p['text'] + '</button>';
                } else {
                    tbtnstr = tbtnstr + p.jstr;
                }
            }
        }

        var IsDetailView = false;
        if (pobj.detailLink.length > 0) {
            IsDetailView = true;
        }

        $('table[name="' + pobj.tableName + '"]:not(.table)').attr('data-unique', rand);
        $('table[name="' + pobj.tableName + '"]:not(.table)').bootstrapTable({
            columns: pobj.cols,
            data: pobj.data.data,
            toolbar: tbtnstr,
            pagination: true,
            search: true,
            searchOnEnterKey: true,
            singleSelect: pobj.isMultiple,
            locale: 'zh-CN',
            showColumns: pobj.showColumns,
            showToggle: pobj.showToggle,
            cardView: pobj.cardView,
            detailView: IsDetailView,
            pagination: true,
            pageSize: pobj.pageSize,
            rowAttributes: function (row, index) {
                return {
                    'data-idx': row.id
                };
            },
            detailFormatter: function (index, row, element) {
                var mdiv = $('<div></div>');
                mdiv.css('margin-left', 32);
                mdiv.css('margin-right', 32);
                var tabs = $('<ul></ul>');
                tabs.addClass('nav');
                tabs.addClass('nav-tabs');
                mdiv.append(tabs);

                for (var i = 0; i < pobj.detailLink.length; i++) {
                    var p = pobj.detailLink[i];
                    var li = $('<li></li>');
                    li.attr('role', 'presentation');
                    if (p.isActive) {
                        li.addClass('active');
                        mdiv.append(loadDetail(row[p.parentid], index, p.tablename));
                    }
                    var a = $('<a></a>');
                    a.attr('href', '#');
                    a.attr('data-tablename', p.tablename);
                    a.html(p.caption);
                    li.append(a);
                    tabs.append(li);
                    a.click(function () {
                        $(this).parent().siblings().removeClass('active');
                        $(this).parent().addClass('active');
                        mdiv.find('div[name="detail"]').remove();
                        mdiv.append(loadDetail(row[p.parentid], index, $(this).attr('data-tablename')));
                    });
                }
                return mdiv;
            }
        });

        //子表需要刷新
        if ($('table[name="' + pobj.tableName + '"][data-unique="' + rand + '"]').parents('div[name="detail"]').length > 0) {
            $('table[name="' + pobj.tableName + '"][data-unique="' + rand + '"]')
                .find('input[name="btSelectAll"]').click(function () {
                    var rand_ = $(this).parents('table:eq(0)').attr('data-unique');
                    var check = $('table[name="' + pobj.tableName + '"][data-unique="' + rand_ + '"]')
                        .find('tr.selected').length == 0 ? 'uncheck' : 'check';
                    $('table[name="' + pobj.tableName + '"][data-unique="' + rand_ + '"]').find('input[data-index="0"][name="btSelectItem"]:eq(0)').click();
                    setTimeout(function () {
                        console.log('check');
                        $('table[name="' + pobj.tableName + '"][data-unique="' + rand_ + '"]').find('input[data-index="0"][name="btSelectItem"]:eq(0)').click();
                    }, 50);
                });
        }
    }

    function loadDetail(idx, rid, tableName) {
        cur_detail_rid = rid;

        var div = $('<div></div>');
        div.attr('data-idx', idx);
        div.attr('data-rid', rid);
        div.attr('name', 'detail');
        div.load('..//' + tableName + '//' + tableName + '.html', null, function () {
            div.find('title').remove();
            div.find('meta').remove();
            div.find('link').remove();
            div.find('script[name!="loadPage"]').remove();
        });
        return div;
    }

    var gridObj = {
        back: function () {
            $('div[name="edit"]').hide();
            $('div[name="table"]').show();
        },
        load: function (page) {
            $('div[name="edit"]').hide();
            $('div[name="table"]').show();
            $('div[name="table"]>div[name="content"]').load(page, null, function () {
                var div = $('div[name="table"]>div[name="content"]');
                div.find('title').remove();
                div.find('meta').remove();
                div.find('link').remove();
                div.find('script[name!="loadPage"]').remove();
            });
        },
        refreash: function (page) {
            $('div[name="edit"]').hide();
            $('div[name="table"]').show();
            $('div[name="table"]>div[name="content"]').load(page, null, function () {
                var div = $('div[name="table"]>div[name="content"]');
                div.find('title').remove();
                div.find('meta').remove();
                div.find('link').remove();
                div.find('script[name!="loadPage"]').remove();
            });
        },
        edit: function (idx, rand_) {
            //$('div[name="table"]').hide();
            //$('div[name="edit"]').show();
            $('div[name="edit"]').attr('data-idx', idx);
            $('div[name="edit"]').attr('data-unique', rand_);
        },
        editLoad: function (page) {
            $('div[name="table"]').hide();
            $('div[name="edit"]').show();
            $('div[name="edit"]>div[name="content"]').attr('data-idx', cur_detail_rid);
            $('div[name="edit"]>div[name="content"]').load(page, null, function () {
                var div = $('div[name="table"]>div[name="content"]');
                div.find('title').remove();
                div.find('meta').remove();
                div.find('link').remove();
                div.find('script[name!="loadPage"]').remove();
            });
        },
        getId_edit: function () {
            return $('div[name="edit"]').attr('data-idx');
        },
        getObj_edit: function () {
            var idx = $('div[name="edit"]').attr('data-idx');
            var rand_ = $('div[name="edit"]').attr('data-unique');
            //console.log(rand_);
            //console.log(JSON.stringify(pobj));
            if (pobj['data' + rand_] == undefined) {
                return null;
            }
            for (var i = 0; i < pobj['data' + rand_].length; i++) {
                var p = pobj['data' + rand_][i];
                //console.log(p.id);
                //console.log(idx);
                if (p.id == idx) {
                    //console.log('true');
                    return p;
                }
            }
            return null;
        },
        getId_detail_grid: function () {
            return $('div[name="detail"][data-rid="' + cur_detail_rid + '"]').attr('data-idx');
        },
        getId_detail_edit: function () {
            cur_detail_rid = $('div[name="edit"]>div[name="content"]').attr('data-idx');
            return $('div[name="detail"][data-rid="' + cur_detail_rid + '"]').attr('data-idx');
        },
        getSelects: function () {
            var objs = $('div[name="detail"][data-rid="' + cur_detail_rid + '"]').length == 0 ?
                function () {
                    var objs_ = [];
                    var op = $('table[name="' + pobj.tableName + '"]');
                    op.find('tr.selected').each(function (idx, ele) {
                        var uid = $(ele).attr('data-idx');
                        $(pobj.data.data).each(function (i, e) {
                            if (e.id == uid) {
                                objs_.push(e);
                            }
                        });
                    });
                    return objs_;
                }() : function () {
                    var objs_ = [];
                    var op = $('div[name="detail"][data-rid="' + cur_detail_rid + '"]')
                        .find('table[name="' + pobj.tableName + '"]');
                    var rand_ = op.attr('data-unique');
                    op.find('tr.selected').each(function (idx, ele) {
                        var uid = $(ele).attr('data-idx');
                        $(pobj['data' + rand_]).each(function (i, e) {
                            if (e.id == uid) {
                                objs_.push(e);
                            }
                        });
                    });
                    return objs_;
                }();
            var objs1 = [];
            $(objs).each(function (idx, ele) {
                var q = $.extend(true, {}, ele);
                delete q[0];
                delete q.order;
                objs1.push(q);
            });
            return objs1;
        },
        showalert: function (obj) {
            cur_detail_rid = $(obj).parents('div[name="detail"]').attr('data-rid');
            cur_detail_rid = parseInt(cur_detail_rid);
        },
        obj: pobj,
        init: init,
        initTable: initTable,
        initCard_mobile: initCard_mobile,
        reCreate: function () {
            rand = parseInt(Math.random() * 1000).toString();
            return this;
        }
    }

    return gridObj;
}